# tools/request_utils.py
""" 
author: Men Dong Yang
create_time: 2025/6/19 14:40:10
description: 和请求相关的函数
"""
import re
from datetime import datetime

import requests
from loguru import logger

date = re.sub(r'[ :-]', '_', str(datetime.now()).split('.')[0])
logger.add(f"logs/log_{date}.log", level="INFO", encoding="utf-8", enqueue=True, rotation="500MB", retention="1 week")


def execute_request(api):
    """发送请求并返回响应"""
    # 拆出api对象中的行头体
    method = api.method
    url = api.host + api.path
    headers = api.headers
    params = api.params
    body = api.body
    # 打印日志
    logger.info(f'发送请求: method:{method}, url: {url}, headers: {headers}, params: {params}, body: {body}')
    # 发送请求
    response = requests.request(method=method, url=url, params=params, headers=headers, json=body)
    # 打印日志
    if response.status_code ==200:
        logger.info(f'返回响应: HTTP状态码: {response.status_code}, 响应信息: {response.text}')
    else:
        logger.error(f'返回响应: HTTP状态码: {response.status_code}, 响应信息: {response.text}')
    return response


def assert_result(response, status_code, expect_msg):
    """输入响应,预期状态码,预期响应信息,断言是否符合预期"""
    assert response.status_code == status_code
    assert response.text.__contains__(expect_msg)
